package cn.wolfcode.wolf2w.interceptor;

//前后端分离返回的前前后后都是JSON格式的数据

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.cache.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录检查
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    //实现登录拦截

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception{

        //排除跨域问题
        //HandlerMethod 代指:动态请求
        //HandlerMethod 请求映射方法在springmvc封装对象

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

//        System.out.println(request.getRequestURI());
//        System.out.println(request.getMethod());

//        String token = request.getHeader("token");
//        UserInfo user = userInfoRedisService.getUserByToken(token);
//        if (user == null){
//            //没有登录,返回告知客户没有登录的提示
//            response.setContentType("application/json;charset=utf-8");//json格式的中文转码,防止某一些电脑无法转码中文
//            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
//            return false;
//        }
        //1.判断当前请求方法是否有注解@RequireLogin
        HandlerMethod hm = (HandlerMethod) handler;
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);

        //2.如果有进行登录校验
        if (hm.hasMethodAnnotation(RequireLogin.class)){
            if (user == null){
                //没有登录
                response.setContentType("application/json;charset=utf-8");//json格式的中文转码,防止某一些电脑无法转码中文
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        //3.如果没有直接放行
        return true;
    }
}
